import { ref, watch } from 'vue'
import { defineStore } from 'pinia'

export const useUserInfoStore = defineStore('userInfo', () => {
  const menuList = ref([])
  const token = ref('')
  const routerList = ref([])
  const updateMenuList = menus => {
    menuList.value = menus
  }
  const addMenu = (router,type )=> {
    console.log('addMenu')
    if(type === 'refresh'){
      console.log('addMenu refresh')
      if(localStorage.getItem("menuList") ){
        console.log('addMenu refresh menuList.value')
        menuList.value = JSON.parse(localStorage.getItem("menuList"))
        token.value = localStorage.getItem("token")
        routerList.value = []
        console.log(menuList.value)
      }else{
        return
      }
    }
    const menu = menuList.value
    //导入文件
    const module = import.meta.glob('../views/**/*.vue')
    const routes = []
    menu.forEach(item => {
      if(item.children){
        item.children.forEach(val =>{
          let url = `../views/${val.url}.vue`
          val.component = module[url]
          routes.push(...item.children)
        })
      }else{
        let url = `../views/${item.url}.vue`
        item.component = module[url]
        routes.push(item)

      }
    })
    //处理多账号登陆路由bug
    router.getRoutes().forEach(item=>{
      if(item.name==='Main' || item.name==='Login' || item.name==='404'){

      }else{
        router.removeRoute(item.name)
      }
    })

    routes.forEach(item=>{
      routerList.value.push(router.addRoute('Main',item))
    })
  }

  const logout = () => {
    routerList.value.forEach(item=>{
      if(item){
        item()
      }
    })
    localStorage.removeItem('token')
    localStorage.removeItem('menuList')
  }

  watch(token, (newVal, oldVal)=>{
    if(newVal){
      localStorage.setItem('token',newVal);
    }
  })
  watch(menuList, (newVal, oldVal)=>{
    if(newVal){
      localStorage.setItem('menuList',JSON.stringify(newVal));
    }
  },{deep:true})
  return {
    menuList,
    token,
    updateMenuList,
    routerList,
    addMenu,
    logout,
  }
})
